package logic

import (
	"cart-go/model"
	"context"
	"errors"
	"gorm.io/gorm"

	"cart-go/cartrpc/cartrpc"
	"cart-go/cartrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cartrpc.CartAddRequest) (*cartrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	var Good model.Good
	model.DB.Debug().Where("id=?", in.GoodID).Find(&Good)
	if in.GoodID == 0 {
		return nil, errors.New("商品不存在,请添加")
	}
	if in.Quantity == Good.Stock {
		return nil, errors.New("库存不足")
	}
	good := model.Good{
		Model: gorm.Model{},
		Name:  in.Name,
		Price: float64(in.Price),
	}

	model.DB.Debug().Create(&good)

	goods := model.Good{
		Model: gorm.Model{},
		Name:  in.Name,
		Price: float64(in.Price),
	}

	model.DB.Debug().Updates(&goods)
	return &cartrpc.CartAddResponse{
		Success: "购物车添加成功",
		Message: false,
	}, nil
}
